#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/wait.h>
#include <string.h>
#define ERROR_CHECK(ret, num, msg) \
    {                              \
        if (ret == num)            \
        {                          \
            perror(msg);           \
            exit(1);               \
        }                          \
    }
#define ARGS_CHECK(argc, num)               \
    {                                       \
        if (argc != num)                    \
        {                                   \
            fprintf(stderr, args error !n); \
            return -1;                      \
        }                                   \
    }
void searchWord(char *dest_word, char *filename)
{
     int fd = open(filename, O_RDONLY);
    ERROR_CHECK(-1, fd, "open");
    int line = 1;
    char *p = "\t \n";
    char *word = NULL;
    int line_lenth = 32;
    char *lineBuf = (char *)malloc(32*sizeof(char));
    char ch = '\0';
    int lenline = 0;
    while (read(fd, &ch, 1))
    {
       

        if (ch == '\n')
        {

            lineBuf[lenline] = '\0';
            word = strtok(lineBuf, p);
            
            while (word)
            {
                printf("%s--%s",word,dest_word);
                printf("%d\n",strcmp(word,dest_word));
                if (strcmp(word,dest_word) == 0)
                {
                    printf("lines = %d\n", line);
                    close(fd);
                    free(lineBuf);
                    return ;
                }
                word =strtok(NULL,p);
            }
             line++;
            lenline = 0;
        }
        lineBuf[lenline++] = ch;
        if (32 <lenline)
        {
            lineBuf = (char *)realloc(lineBuf,lenline*2*sizeof(char));
        }
        
    }
    printf("not found\n");
    close(fd);
    return;
}

/**
 * @brief
 *
 * @param argc
 * @param argv  ./   word  file1 file2 filen ...
 * @return int
 */
int main(int argc, char *argv[])
{

    // for (size_t i = 2; i < argc; i++)
    // {
    //     __pid_t pid = fork();
    //     if (pid == 0)
    //     {
    //         searchWord(argv[1],argv[i]);
    //         exit(EXIT_SUCCESS);
    //     }
    //     if (pid > 0)
    //     {
    //         break;
    //     }
         
    // }    
    int n = 0;
     __pid_t pid;
    for (size_t i = 2; i < argc; i++)
    {
        pid = fork();
        if (pid == 0)
        {
           n =i;
           break;
        }     
    }
    if (pid == 0)
    {
        searchWord(argv[1],argv[n]);
    }
  if (pid > 0)
  {
        sleep(1);
  }
    return 0;
}
